package com.wan.net.core.websocket;

import com.wan.net.config.HostAndPort;
import com.wan.net.core.AbstractServer;
import com.wan.net.core.ServerType;
import com.wan.util.Constants;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.annotation.Nullable;
/**
 * @author wwh
 * @date 2022/6/16 14:57
 */
public class WebsocketServer extends AbstractServer {

    public WebsocketServer(HostAndPort hostAndPort) {
        super(hostAndPort);
    }

    public WebsocketServer(HostAndPort hostAndPort, int idleTimeout) {
        super(hostAndPort, idleTimeout);
    }

    public WebsocketServer(HostAndPort hostAndPort, @Nullable ChannelHandler channelHandler) {
        super(hostAndPort, channelHandler);
    }

    public WebsocketServer(HostAndPort hostAndPort, int idleTimeout, @Nullable ChannelHandler channelHandler) {
        super(hostAndPort, idleTimeout, channelHandler);
    }

    @Override
    protected void channelChannelInitializer(ChannelPipeline pipeline) {
        // 编解码 http 请求
        pipeline.addLast(new HttpServerCodec(8 * Constants.BYTE_OF_KB, 16 * Constants.BYTE_OF_KB, 16 * Constants.BYTE_OF_KB));
        // 聚合解码 HttpRequest/HttpContent/LastHttpContent 到 FullHttpRequest
        // 保证接收的 Http 请求的完整性
        pipeline.addLast(new HttpObjectAggregator(16 * Constants.BYTE_OF_MB));
        // 处理其他的 WebSocketFrame
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // 写文件内容，支持异步发送大的码流，一般用于发送文件流
        pipeline.addLast(new ChunkedWriteHandler());
        // 编解码WebSocketFrame二进制协议
        pipeline.addLast(new WebsocketCodec());
    }

    @Override
    public ServerType getServerType() {
        return ServerType.WEB_SOCKET;
    }
}
